const mongoose = require('mongoose');
const { query, pool } = require('./src/config/mysqlConfig');
const Message = require('./src/models/Message');
const User = require('./src/models/User');

// 连接MongoDB数据库
mongoose.connect('mongodb://localhost:27017/litechat')
  .then(async () => {
    console.log('MongoDB 连接成功');
    
    try {
      // 获取所有用户
      const users = await User.find({});
      console.log(`MongoDB中有 ${users.length} 名用户`);
      
      // 从消息记录中提取好友关系
      const messages = await Message.find({});
      console.log(`找到 ${messages.length} 条消息记录`);
      
      // 使用Set来存储独特的用户对
      const friendPairs = new Set();
      
      // 从消息记录中提取发送者和接收者对
      messages.forEach(msg => {
        const sender = msg.sender.toString();
        const receiver = msg.receiver.toString();
        
        // 使用排序确保同一对用户生成相同的字符串键
        const key = [sender, receiver].sort().join(':');
        friendPairs.add(key);
      });
      
      console.log(`提取出 ${friendPairs.size} 对可能的好友关系`);
      
      // 建立连接池
      const connection = await pool.getConnection();
      
      try {
        await connection.beginTransaction();
        
        // 遍历并插入好友关系
        for (const pair of friendPairs) {
          const [user1, user2] = pair.split(':');
          
          // 检查用户是否存在
          const user1Exists = users.some(u => u._id.toString() === user1);
          const user2Exists = users.some(u => u._id.toString() === user2);
          
          if (!user1Exists || !user2Exists) {
            console.log(`跳过关系 ${user1} <-> ${user2}，有用户不存在`);
            continue;
          }
          
          // 检查这对好友关系是否已存在
          const existingRelation = await connection.query(
            'SELECT COUNT(*) as count FROM friends WHERE user_id = ? AND friend_id = ?',
            [user1, user2]
          );
          
          // 如果关系不存在，则插入
          if (existingRelation[0][0].count === 0) {
            console.log(`添加好友关系: ${user1} -> ${user2}`);
            await connection.query(
              'INSERT INTO friends (user_id, friend_id) VALUES (?, ?)',
              [user1, user2]
            );
          }
          
          // 检查反向关系是否存在
          const existingReverseRelation = await connection.query(
            'SELECT COUNT(*) as count FROM friends WHERE user_id = ? AND friend_id = ?',
            [user2, user1]
          );
          
          // 如果反向关系不存在，则插入
          if (existingReverseRelation[0][0].count === 0) {
            console.log(`添加好友关系: ${user2} -> ${user1}`);
            await connection.query(
              'INSERT INTO friends (user_id, friend_id) VALUES (?, ?)',
              [user2, user1]
            );
          }
        }
        
        await connection.commit();
        console.log('好友关系迁移完成！');
        
        // 检查好友关系迁移结果
        const [friendRows] = await connection.query('SELECT * FROM friends');
        console.log(`现在MySQL中共有 ${friendRows.length} 条好友关系记录`);
        
        // 输出最终用户关系状态
        for (const user of users) {
          const userId = user._id.toString();
          const [userFriends] = await connection.query('SELECT friend_id FROM friends WHERE user_id = ?', [userId]);
          console.log(`用户 ${user.username}(${userId}) 的好友数量: ${userFriends.length}`);
          
          if (userFriends.length > 0) {
            const friendIds = userFriends.map(f => f.friend_id);
            const friends = users.filter(u => friendIds.includes(u._id.toString()));
            console.log(`  好友列表: ${friends.map(f => f.username).join(', ')}`);
          }
        }
        
      } catch (error) {
        await connection.rollback();
        console.error('迁移出错，已回滚:', error);
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error('迁移过程中出错:', error);
    } finally {
      // 关闭数据库连接
      await mongoose.disconnect();
      await pool.end();
      console.log('数据库连接已关闭');
    }
  })
  .catch(err => {
    console.error('MongoDB 连接失败:', err);
  }); 